<?php

/**
 * This is the model class for table "v__item".
 *
 * The followings are the available columns in table 'v__item':
 * @property integer $Id
 * @property integer $hasImage
 * @property string $Name
 */
class Item extends CActiveRecord
{
	
	public static function findVotePair($userId){
		$criteria = new CDbCriteria;
		
		$criteria -> order = 'RAND()';
		$criteria -> limit = 2;
		
		$items = Item::model() -> findAll($criteria);
		
		if(count($items) != 2)
			throw new CHttpException('500','Недостаточно объектов для голосования');
			
		return $items;
	}
	
	/**
	 * Получить ссылку на страницу объекта
	 */
	public function getLink(){
		return CHtml::link($this -> Name, array('item/view', 'id' => $this -> Id));
	}
	
	/**
	 * Получить общее количество голосов в системе
	 */
	public static function getTotalVotesNum(){
		$table = self::model() -> tableName();
		$sql   = "SELECT SUM(Compares) FROM $table";
		
		$num = Yii::app() -> db -> createCommand($sql) -> queryScalar();
		return intval($num) / 2;
	}
	
	public function getImage(){
		return CHtml::image('poiskdemo/itemimages/'.$this->Id.'.jpg');
	}
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return Item the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'v__item';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('Name', 'required'),			
			array('Name', 'length', 'max'=>256),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'Id' => 'ID',
			'Name' => 'Наименование',
			'Link' => 'Имя',
			'Points' => 'Число голосов',
			'Compares' => 'Число сравнений'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('Id',$this->Id);
		$criteria->compare('Name',$this->Name,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	public function save(){
		if(!parent::save()) return false;
		
		$file  = CUploadedFile::getInstance($this, 'IconFile');
		if(empty($file)){
			return true;
		}
		
		if($file->extensionName != 'jpg' && $file->extensionName != 'jpeg'){
			$this -> addError('IconFile','Принимается только jpg');
			return false;
		}
		
		$path  = YiiBase::getPathOfAlias('webroot.itemimages');		
		$path .= '/'.$this -> Id .'.jpg';

		return $file -> saveAs($path);
	}	
}